﻿using Microsoft.SharePoint;
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace VPLink2013.Framework
{
    public static class FileSerialization
    {
        #region deserialize xml

        public static T CreateObjFromXMLString<T>(string xmlContent)
        {
            T cachedObj = default(T);
            if (!string.IsNullOrEmpty(xmlContent))
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        XmlSerializer objSerializer = new XmlSerializer(typeof(T));
                        using (TextReader xmlStreamReader = new StringReader(xmlContent))
                        {
                            cachedObj = (T)objSerializer.Deserialize(xmlStreamReader);
                        }
                    });
                }
                catch (System.Exception exc)
                {
                    ContextTrace.AddTrace("Erreur.DeserializeUtilisateurCrt : " + exc.Message + "/" + exc.StackTrace);
                }
            }
            return cachedObj;
        }

        public static T CreateObjFromXML<T>(string xmlCachedFilePath)
        {
            T cachedObj = default(T);
            if (!string.IsNullOrEmpty(xmlCachedFilePath))
            {
                if (CheckFileCacheExists(xmlCachedFilePath))
                {
                    try
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            XmlSerializer objSerializer = new XmlSerializer(typeof(T));
                            FileStream fileStream = new FileStream(xmlCachedFilePath, FileMode.Open, FileAccess.Read);
                            using (StreamReader xmlStreamReader = new StreamReader(fileStream, Encoding.UTF8, true))
                            {
                                cachedObj = (T)objSerializer.Deserialize(xmlStreamReader);
                            }
                            fileStream.Close();
                        });
                    }
                    catch (System.Exception exc)
                    {
                        ContextTrace.AddTrace("Erreur.DeserializeUtilisateurCrt : " + exc.Message + "/" + exc.StackTrace);
                    }
                }
                else
                {
                    ContextTrace.AddTrace( string.Format("Le fichier {0} n'existe pas!", xmlCachedFilePath));
                }
            }
            return cachedObj;
        }

        #endregion

        #region serialize xml

        public static string CreateXmlStringFromObj(object objToSerialize)
        {
            string strXml = string.Empty;
            if (objToSerialize != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    XmlSerializer serializer = new XmlSerializer(objToSerialize.GetType());
                    using (TextWriter tw = new StringWriter(new StringBuilder()))
                    {
                        serializer.Serialize(tw, objToSerialize);
                        strXml = tw.ToString();
                        strXml = strXml.Replace("utf-16", "iso-8859-1");
                    }
                });
            }
            return strXml;
        }

        public static void CreateXmlFromObj(object objToSerialize, string xmlFilePath)
        {
            string strXml = string.Empty;
            if (objToSerialize != null)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    System.IO.FileInfo file = new System.IO.FileInfo(xmlFilePath);
                    file.Directory.Create();
                    XmlSerializer serializer = new XmlSerializer(objToSerialize.GetType());
                    XmlTextWriter tw = new XmlTextWriter(xmlFilePath, Encoding.UTF8);
                    serializer.Serialize(tw, objToSerialize);
                    tw.Close();
                });
            }
        }

        #endregion
        public static bool CheckFileCacheExists(string fileCache)
        {
            bool exists = false;
            if (!string.IsNullOrEmpty(fileCache))
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        if (System.IO.File.Exists(fileCache))
                        {
                            exists = true;
                        }
                    });
                }
                catch (System.Exception exc)
                {
                    ContextTrace.AddTrace( "Error.CheckFileCache : " + exc.Message + "/" + exc.StackTrace );
                }
            }
            return exists;
        }

        public static bool CheckFileCacheExists(string fileCache, int minutes)
        {
            bool exists = false;
            if (!string.IsNullOrEmpty(fileCache))
            {
                try
                {
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        if (System.IO.File.Exists(fileCache))
                        {
                            DateTime dtFileCreated = System.IO.File.GetLastWriteTime(fileCache);
                            TimeSpan tsDiff = DateTime.Now - dtFileCreated;
                            if (tsDiff.TotalMinutes > minutes)
                            {
                                DeleteFile(fileCache);
                            }
                            else
                            {
                                exists = true;
                            }
                        }
                    });
                }
                catch (System.Exception exc)
                {
                    ContextTrace.AddTrace("Error.CheckFileCache : " + exc.Message + "/" + exc.StackTrace);
                }
            }
            return exists;
        }

        private static void DeleteFile(string strFilePath)
        {
            if (!string.IsNullOrEmpty(strFilePath))
            {
                if (System.IO.File.Exists(strFilePath))
                {
                    try
                    {
                        System.IO.File.Delete(strFilePath);
                    }
                    catch (System.Exception exc)
                    {
                        ContextTrace.AddTrace("Erreur delete file : " + strFilePath + " / " + exc.Message);
                    }
                }
            }
        }
        public static void TraceFile(string filePath, string body)
        {
            try
            {
                System.IO.FileInfo file = new System.IO.FileInfo(filePath);
                file.Directory.Create();
                using (StreamWriter sw = new StreamWriter(File.Open(filePath, FileMode.Create), Encoding.UTF8))
                {
                    sw.WriteLine(body);
                }
            }
            catch (System.Exception exc)
            {
                ContextTrace.AddTrace("TraceFile : " + exc.Message + "/" + exc.StackTrace);
            }
        }

    }
}
